package com.shinechain.botModel;

import com.shinechain.TulingBot.Tuling;
import com.shinechain.dao.*;
import com.shinechain.model.*;
import com.shinechain.service.user.TelegramBotMethod;
import com.shinechain.utils.EndGuessThread;
import com.shinechain.utils.RedPacketUtil;
import com.shinechain.utils.RewardUtil;
import jdk.nashorn.internal.parser.Token;
import org.telegram.telegrambots.api.methods.groupadministration.GetChatAdministrators;
import org.telegram.telegrambots.api.methods.groupadministration.GetChatMember;
import org.telegram.telegrambots.api.methods.groupadministration.KickChatMember;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.methods.send.SendPhoto;
import org.telegram.telegrambots.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.api.objects.ChatMember;
import org.telegram.telegrambots.api.objects.MessageEntity;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WorkBot extends TelegramLongPollingBot implements TelegramBotMethod, Runnable {
    private long chatId = -1001389649632L;
    private Update update = new Update();
    public static UsersMapper usersMapper;
    public static InviteRewardMapper inviteRewardMapper;
    public static RewardMapper rewardMapper;
    public static RewardUserMapper rewardUserMapper;
    public static GuessMapper guessMapper;
    public static GuessUserMapper guessUserMapper;
    public static TelegramUserMapper telegramUserMapper;
    public static CheckInMapper checkInMapper;
    public static ChatTokenMapper chatTokenMapper;
    public static String bitName = "token";

    @Override
    public void onUpdateReceived(Update update) {
        this.update = update;
        if (update.hasCallbackQuery()) {
            hasGuessing();
        } else if (update.hasMessage()) {
            if (update.getMessage().isCommand()) {
                this.candy();
            }

            boolean isAdmin = false;
            for (int i = 0; i < BotMethodSwitch.adminList.size(); i++) {
                if (update.getMessage().getFrom().getId().intValue() == BotMethodSwitch.adminList.get(i).getUser().getId().intValue()) {
                    //是管理员
                    isAdmin = true;
                }
            }
            if (isAdmin) {
                if (hasNewMenber(update)) {
                    this.deleteJoinOUTMsg(BotMethodSwitch.botMethod.get("deleteJoinOutMsg"));
                    this.welcome(BotMethodSwitch.botMethod.get("useWelcome"), BotMethodSwitch.welcome);
                    this.inviteToken(BotMethodSwitch.botMethod.get("useToken"), BotMethodSwitch.token);
                } else {
                    this.useTuling(BotMethodSwitch.botMethod.get("useTuling"));
                }

                //处理其他信息
            } else {
                if (this.disableSpam(BotMethodSwitch.botMethod.get("disableSpam"))) {
                    kitManWhoDeleteThreeMsg();
                }
                if (this.deleteForward(BotMethodSwitch.botMethod.get("deleteForward"))) {
                    kitManWhoDeleteThreeMsg();
                }
                //处理文字信息
                else if (update.getMessage().hasText()) {
                    if(this.checkIn()){}
                    //检查是否白名单，若是则跳过
                    else if (!this.whiteList(BotMethodSwitch.botMethod.get("useWhiteList"), BotMethodSwitch.whiteList)) {
                        if (this.deleteAdKey(BotMethodSwitch.botMethod.get("deleteAdKeyFlag"), BotMethodSwitch.blackList)) {
                            kitManWhoDeleteThreeMsg();
                        } else if (this.deleteSendLink(BotMethodSwitch.botMethod.get("deleteSendLink"))) {
                            kitManWhoDeleteThreeMsg();
                        } else if (this.disableSpam(BotMethodSwitch.botMethod.get("disableSpam"))) {
                            kitManWhoDeleteThreeMsg();
                        } else if (this.chat(BotMethodSwitch.botMethod.get("useChat"), BotMethodSwitch.chatHashMap)) {
                        } else if (this.useTuling(BotMethodSwitch.botMethod.get("useTuling"))) {
                        }
                    }
                }
                //处理新成员加入
                else if (hasNewMenber(update)) {
                    this.deleteJoinOUTMsg(BotMethodSwitch.botMethod.get("deleteJoinOutMsg"));
                    if (!disableAddBot(BotMethodSwitch.botMethod.get("disableAddBot"))) {
                        if (!deleteLongUsername(BotMethodSwitch.botMethod.get("deleteLongUsername"))) {
                            this.welcome(BotMethodSwitch.botMethod.get("useWelcome"), BotMethodSwitch.welcome);
                            this.inviteToken(BotMethodSwitch.botMethod.get("useToken"), BotMethodSwitch.token);
                        }
                    }
                    //处理其他信息
                } else if (this.deletePhoto(BotMethodSwitch.botMethod.get("deletePhoto"))) {
                    kitManWhoDeleteThreeMsg();
                } else if (this.deleteFile(BotMethodSwitch.botMethod.get("deleteFile"))) {
                    kitManWhoDeleteThreeMsg();
                } else if (this.deleteVoice(BotMethodSwitch.botMethod.get("deleteVoice"))) {
                    kitManWhoDeleteThreeMsg();
                } else if (this.deleteVideo(BotMethodSwitch.botMethod.get("deleteVideo"))) {
                    kitManWhoDeleteThreeMsg();
                } else if (this.deleteOutMsg(BotMethodSwitch.botMethod.get("deleteJoinOutMsg"))) {
                    kitManWhoDeleteThreeMsg();
                }
            }

        }

    }


    @Override
    public String getBotUsername() {
        return "ShineChainWork_bot";
        //return "ShineChainTest_bot";
    }

    @Override
    public String getBotToken() {
        return "677123674:AAEAhXuA4D5KkrbcFL_chxBxQm0_2R_cjYU";
        //return "642292440:AAEfRHbeNj9KjVlN6ObBlhx0dpCCXyYk_Ho";
    }

    public WorkBot(DefaultBotOptions options) {
        super(options);
    }

    public void sendMessage(long chatId, String text) {
        SendMessage message = new SendMessage() // Create a SendMessage object with mandatory fields
                .setChatId(chatId)
                .setText(text);
        try {
            execute(message); // Call method to send the message
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    public void messageDelete(Update update) {
        if (BotMethodSwitch.botMethod.get("useDeleteMsg")) {
            DeleteMessage deleteMessage = new DeleteMessage();
            deleteMessage.setMessageId(update.getMessage().getMessageId())
                    .setChatId(update.getMessage().getChatId());
            try {
                execute(deleteMessage); // Call method to send the message
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
    }

    public void messageDelete(int id) {
        if (BotMethodSwitch.botMethod.get("useDeleteMsg")) {
            DeleteMessage deleteMessage = new DeleteMessage();
            deleteMessage.setMessageId(id)
                    .setChatId(update.getMessage().getChatId());
            try {
                execute(deleteMessage); // Call method to send the message
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
    }

    public boolean hasNewMenber(Update update) {
        boolean hasJoinOut = false;
        try {
            hasJoinOut = !this.update.getMessage().getNewChatMembers().isEmpty();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return hasJoinOut;
    }

    @Override
    public boolean kitManWhoDeleteThreeMsg() {
        if (BotMethodSwitch.botMethod.get("useKitMan")) {
            if (BotMethodSwitch.botMethod.get("kitManWhoDeleteThreeMsg")) {
                if (BotMethodSwitch.deleteMsgCount.containsKey(this.update.getMessage().getFrom().getId())) {
                    int i = BotMethodSwitch.deleteMsgCount.get(this.update.getMessage().getFrom().getId()) + 1;
                    System.out.println("deleteMsgCount" + i);
                    if (i >= 3) {
                        KickChatMember kickChatMember = new KickChatMember();
                        kickChatMember.setUserId(this.update.getMessage().getFrom().getId());
                        kickChatMember.setChatId(this.update.getMessage().getChatId());
                        try {
                            execute(kickChatMember); // Call method to send the message
                        } catch (TelegramApiException e) {
                            e.printStackTrace();
                        }
                    } else {
                        BotMethodSwitch.deleteMsgCount.put(this.update.getMessage().getFrom().getId(), i);
                    }
                } else {
                    BotMethodSwitch.deleteMsgCount.put(this.update.getMessage().getFrom().getId(), 1);
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deletePhoto(boolean flag) {
        if (flag) {
            if (this.update.getMessage().hasPhoto()) {
                this.messageDelete(this.update);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteFile(boolean flag) {
        if (flag) {
            if (this.update.getMessage().hasDocument()) {
                this.messageDelete(this.update);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteVoice(boolean flag) {
        if (flag) {
            if (this.update.getMessage().getVoice() != null) {
                this.messageDelete(this.update);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteVideo(boolean flag) {
        if (flag) {
            if (this.update.getMessage().hasVideo()) {
                this.messageDelete(this.update);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteForward(boolean flag) {
        if (flag) {
            if (this.update.getMessage().getForwardFrom() != null) {
                this.messageDelete(this.update);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteJoinOUTMsg(boolean flag) {
        if (flag) {
            this.messageDelete(this.update);
            return true;
        }
        return false;
    }

    public boolean deleteOutMsg(boolean flag) {
        if (flag) {
            boolean hasJoinOut = false;
            try {
                hasJoinOut = this.update.getMessage().getLeftChatMember() != null;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (hasJoinOut) {
                this.messageDelete(this.update);
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean deleteSendLink(boolean flag) {
        if (flag) {
            List<MessageEntity> list = this.update.getMessage().getEntities();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getType().equals("url")) {
                        this.messageDelete(this.update);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean deleteLongUsername(boolean flag) {
        if (BotMethodSwitch.botMethod.get("useKitMan")) {
            if (flag) {
                boolean nameLongUser = false;
                for (int i = 0; i < this.update.getMessage().getNewChatMembers().size(); i++) {
                    int nameLong = 0;
                    String name = this.update.getMessage().getNewChatMembers().get(i).getFirstName()+this.update.getMessage().getNewChatMembers().get(i).getLastName();
                    boolean isAdName = false;
                    for(int j=0;j<BotMethodSwitch.adName.size();j++){
                        String regEx = BotMethodSwitch.adName.get(j);
                        Pattern pattern = Pattern.compile(regEx);
                        Matcher matcher = pattern.matcher(name);
                        if (matcher.find()) {
                            isAdName = true;
                        }
                    }
                    try {
                        nameLong += this.update.getMessage().getNewChatMembers().get(i).getFirstName().length();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        nameLong += this.update.getMessage().getNewChatMembers().get(i).getLastName().length();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (nameLong > 25 || isAdName) {
                        nameLongUser = true;
                        KickChatMember kickChatMember = new KickChatMember();
                        kickChatMember.setUserId(this.update.getMessage().getNewChatMembers().get(i).getId());
                        kickChatMember.setChatId(this.update.getMessage().getChatId());
                        try {
                            execute(kickChatMember); // Call method to send the message
                        } catch (TelegramApiException e) {
                            e.printStackTrace();
                        }
                    }
                    return nameLongUser;
                }
            }
        }
        return false;
    }


    @Override
    public boolean useTuling(boolean flag) {
        if (flag) {
            List<MessageEntity> list = this.update.getMessage().getEntities();
            if (list != null && list.get(0).getType().equals("mention")) {
                String mychat[] = update.getMessage().getText().split(" ");

                if (mychat[0].equals("@" + this.getBotUsername())) {

                    String resp;
                    String chat = "";
                    for (int i = 1; i < mychat.length; i++) {
                        chat += mychat[i];
                    }
                    try {
                        resp = Tuling.chat(chat);
                        this.sendMessage(this.update.getMessage().getChatId(), resp);
                        return true;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean disableAddBot(boolean flag) {
        boolean haskit = false;
        if (flag) {
            for (int i = 0; i < this.update.getMessage().getNewChatMembers().size(); i++) {
                int nameLong = 0;
                if (this.update.getMessage().getNewChatMembers().get(i).getBot()) {
                    GetChatMember getChatMember = new GetChatMember();
                    getChatMember.setChatId(this.update.getMessage().getChatId());
                    getChatMember.setUserId(this.update.getMessage().getFrom().getId());
                    ChatMember chatMember = new ChatMember();
                    try {
                        chatMember = execute(getChatMember);
                    } catch (TelegramApiRequestException e) {
                        e.printStackTrace();
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                    System.out.println(chatMember.getCanPinMessages());
                    if (!chatMember.getCanPinMessages()) {
                        KickChatMember kickChatMember = new KickChatMember();
                        kickChatMember.setUserId(this.update.getMessage().getNewChatMembers().get(i).getId());
                        kickChatMember.setChatId(this.update.getMessage().getChatId());
                        try {
                            haskit = true;
                            execute(kickChatMember); // Call method to send the message
                        } catch (TelegramApiException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return haskit;
        }
        return false;

    }

    @Override
    public boolean disableSpam(boolean flag) {
        if (flag) {
            boolean hasdelete = false;
            Integer id = update.getMessage().getFrom().getId();
            HashMap<String, LinkedList<SpamMessage>> map = new HashMap<>();
            LinkedList<SpamMessage> list = new LinkedList<>();
            SpamMessage spamMessage = new SpamMessage();
            String msg = null;
            BotMethodSwitch.userTalkInOneMin.put(id, new Date());
            if (update.getMessage().hasText()) {
                msg = update.getMessage().getText();
            } else if (update.getMessage().getSticker() != null) {
                msg = update.getMessage().getSticker().getFileId();
            } else if (update.getMessage().hasDocument()) {
                msg = update.getMessage().getDocument().getFileSize() + "";
            } else if (update.getMessage().hasPhoto()) {
                msg = update.getMessage().getPhoto().get(0).getFileSize() + "";
            }
            if (msg != null) {
                if (BotMethodSwitch.spamCount.containsKey(id) && BotMethodSwitch.spamCount.get(id).containsKey(msg)) { //已存在用户 并存在语句
                    map = BotMethodSwitch.spamCount.get(id);
                    list = map.get(msg);
                    if (list.size() == 1) {
                        spamMessage.setMsgId(update.getMessage().getMessageId());
                        spamMessage.setDate(new Date());
                        list.add(spamMessage);
                        map.put(msg, list);
                        BotMethodSwitch.spamCount.put(id, map);
                    } else if (list.size() == 2) {
                        if (list.get(0).getDate().getTime() + 60000 > new Date().getTime()) {
                            hasdelete = true;
                            this.messageDelete(this.update);
                            this.messageDelete(list.get(0).getMsgId());
                            this.messageDelete(list.get(1).getMsgId());
                            BotMethodSwitch.spamCount.get(id).remove(msg);
                        } else {
                            spamMessage.setMsgId(update.getMessage().getMessageId());
                            spamMessage.setDate(new Date());
                            list.removeFirst();
                            list.addLast(spamMessage);
                            map.put(msg, list);
                            BotMethodSwitch.spamCount.put(id, map);
                        }
                    }
                } else {
                    spamMessage.setDate(new Date());
                    spamMessage.setMsgId(update.getMessage().getMessageId());
                    list.addFirst(spamMessage);
                    map.put(msg, list);
                    BotMethodSwitch.spamCount.put(id, map);
                }
            }
            return hasdelete;
        }
        return false;
    }

    @Override
    public boolean deleteAdKey(boolean flag, List<String> list) {
        if (flag) {
            for (int i = 0; i < list.size(); i++) {
                String regEx = list.get(i);
                Pattern pattern = Pattern.compile(regEx);
                Matcher matcher = pattern.matcher(this.update.getMessage().getText());
                if (matcher.find()) {
                    this.messageDelete(this.update);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean welcome(boolean flag, String msg) {
        if (flag) {
            int count = update.getMessage().getNewChatMembers().size();
            String username = "";
            if (count > 1) {
                for (int i = 0; i < count - 1; i++) {
                    username += update.getMessage().getNewChatMembers().get(i).getFirstName() + " " +
                            update.getMessage().getNewChatMembers().get(i).getLastName() + "、";
                }
                username += update.getMessage().getNewChatMembers().get(count - 1).getFirstName() + " " +
                        update.getMessage().getNewChatMembers().get(count - 1).getLastName();

            } else if (count == 1) {
                username = update.getMessage().getNewChatMembers().get(0).getFirstName() + " " +
                        update.getMessage().getNewChatMembers().get(0).getLastName();
            }
            username.replace("null","");
            msg = msg.replace("*用户*", username);

            this.sendMessage(this.update.getMessage().getChatId(), msg);
            return true;
        }
        return false;
    }

    @Override
    public boolean whiteList(boolean flag, List<String> list) {
        if (flag) {
            for (int i = 0; i < list.size(); i++) {
                String regEx = list.get(i);
                Pattern pattern = Pattern.compile(regEx);
                Matcher matcher = pattern.matcher(this.update.getMessage().getText());
                if (matcher.find()) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean chat(boolean flag, HashMap<String, String> hashMap) {
        if (flag) {
            if (hashMap.containsKey(this.update.getMessage().getText())) {
                this.sendMessage(this.update.getMessage().getChatId(), hashMap.get(this.update.getMessage().getText()));
                return true;
            }
        }
        return false;
    }

    public static boolean sendMsgOnTime(Long chatId, String msg) {

        //sendMessage(chatId,msg);
        return false;
    }

    @Override
    public boolean inviteToken(boolean flag, Double token) {
        if (flag) {
            if (update.getMessage().getFrom().getId().intValue() != update.getMessage().getNewChatMembers().get(0).getId().intValue()) {
                int mount = update.getMessage().getNewChatMembers().size();
                int count = 0;
                boolean hasman = false;
                boolean inviteDayLimit = false;
                InviteReward inviteReward = new InviteReward();
                String msg = "恭喜" + update.getMessage().getFrom().getFirstName() + " " +
                        update.getMessage().getFrom().getLastName() + "，成功拉取";
                List<InviteReward> inviteRewardList = inviteRewardMapper.selectCandyByInviterId(update.getMessage().getFrom().getId());
                int inviteToday = 0;
                String name = "";
                String firstname = update.getMessage().getFrom().getFirstName();
                String lastname = update.getMessage().getFrom().getLastName();
                for (int j = 0; j < inviteRewardList.size(); j++) {
                    if (this.differDayQty(inviteRewardList.get(j).getInserttime(), new Date()) == 0) {
                        inviteToday++;
                    }
                }
                for (int i = 0; i < mount; i++) {

                    if (!update.getMessage().getNewChatMembers().get(i).getBot()) {

                        if (update.getMessage().getNewChatMembers().get(i).getFirstName() != null) {
                            msg += update.getMessage().getNewChatMembers().get(i).getFirstName() + " ";
                        }
                        if (update.getMessage().getNewChatMembers().get(i).getLastName() != null) {
                            msg += update.getMessage().getNewChatMembers().get(i).getLastName() + " ";
                        }
                        if (inviteRewardMapper.hasInvited(update.getMessage().getNewChatMembers().get(i).getId()).size() == 0) {

                            count++;
                            hasman = true;

                            if (firstname != null && !firstname.equals("")) {
                                name += firstname;
                            }
                            if (lastname != null && !lastname.equals("")) {
                                name += lastname;
                            }
                            inviteReward.setInvitername(name);
                            inviteReward.setInviterid(update.getMessage().getFrom().getId());
                            inviteReward.setInvitedid(update.getMessage().getNewChatMembers().get(i).getId());
                            if (inviteToday < BotMethodSwitch.tokenDayTimes) {
                                inviteToday++;
                                inviteReward.setToken(BotMethodSwitch.token);

                            } else {
                                inviteReward.setToken(0.0);
                                inviteDayLimit = true;
                            }

                            inviteReward.setInserttime(new Date());

                            inviteRewardMapper.insert(inviteReward);
                        }
                    }
                }
                if (inviteDayLimit) {
                    msg += "进群,今日邀请用户获得奖励次数已达上限";
                } else {
                    msg += "进群,共获得" + token * mount + "共识token";
                }
                System.out.println(msg);
                if (hasman) {
                    double candycount = count * BotMethodSwitch.candy;
                    List<Users> list = usersMapper.selectByTelegramId(update.getMessage().getFrom().getId());
                    if (list != null && list.size() == 1) {
                        Users users = new Users();
                        users = list.get(0);
                        users.setCandynum(users.getCandynum() + candycount);
                        usersMapper.updateByPrimaryKey(users);
                    } else {
                        TelegramUser telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(update.getMessage().getFrom().getId());
                        if (telegramUser != null) {
                            telegramUser.setToken(telegramUser.getToken() + candycount);
                            WorkBot.telegramUserMapper.updateByPrimaryKey(telegramUser);
                        } else {
                            TelegramUser telegramUserNew = new TelegramUser();
                            telegramUserNew.setToken(candycount);
                            telegramUserNew.setTelegramid(update.getMessage().getFrom().getId());
                            WorkBot.telegramUserMapper.insert(telegramUserNew);
                        }
                    }
                    this.sendMessage(this.update.getMessage().getChatId(), msg);
                }
                return true;
            }

        }
        return false;
    }

    public boolean candy() {
        if (this.update.hasMessage() && this.update.getMessage().isCommand()) {
            String[] texts = update.getMessage().getText().split(" ");
            String username = "";
            username = update.getMessage().getFrom().getFirstName() + " " + update.getMessage().getFrom().getLastName();
            username = username.replace("null", "");
            if (texts[0].equals("/start")) {
                Users users = new Users();
                if (texts[1] != null && !texts[1].equals("") && texts[1].length() == 6) {
                    List<Users> list = usersMapper.selectByInviteCode(texts[1]);
                    if (list != null && list.size() >= 1) {
                        users = list.get(0);

                        if (!users.getTelegram() && users.getTelegramid() == 0) {
                            if (usersMapper.selectByTelegramId(update.getMessage().getFrom().getId()).size() == 0) {
                                TelegramUser telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(update.getMessage().getFrom().getId());
                                users.setTelegram(true);
                                users.setTelegramid(this.update.getMessage().getFrom().getId());

                                users.setCandynum(users.getCandynum() + BotMethodSwitch.candy + telegramUser.getToken());
                                usersMapper.updateByPrimaryKey(users);
                                this.sendMessage(this.update.getMessage().getChatId(), "恭喜您绑定电报群成功" + "获得" + BotMethodSwitch.candy +
                                        WorkBot.bitName + "，并拥有参与群活动奖励" + telegramUser.getToken() + WorkBot.bitName);
                            } else {
                                this.sendMessage(this.update.getMessage().getChatId(), update.getMessage().getFrom().getFirstName() + "您好，此电报号已经绑定过了");
                            }

                        } else {
                            this.sendMessage(this.update.getMessage().getChatId(), update.getMessage().getFrom().getFirstName() + "您好，您已经绑定过了");
                        }
                    } else {
                        this.sendMessage(this.update.getMessage().getChatId(), update.getMessage().getFrom().getFirstName() + "您好，口令错误，请检查并再次尝试");
                    }
                    return false;
                } else {
                    this.sendMessage(this.update.getMessage().getChatId(), update.getMessage().getFrom().getFirstName() + "您好，口令错误，请检查并再次尝试");
                }
                //查询个人
            } else if (texts[0].equals("/mine") || texts[0].equals("/mine" + "@" + getBotUsername())) {
                Users users = new Users();
                List<Users> mylist = usersMapper.selectByTelegramId(update.getMessage().getFrom().getId());
                try {
                    if (mylist != null && mylist.size() >= 1) {
                        users = mylist.get(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (users != null && users.getTelegram()) {
                    double candyTotal = users.getCandynum();
                    double candyInvite = this.getUserAllInviteReward(update.getMessage().getFrom().getId());
                    double redReward = this.getUserAllReward(update.getMessage().getFrom().getId());

                    this.sendMessage(this.update.getMessage().getChatId(), update.getMessage().getFrom().getFirstName() +
                            "您好，您共得到" + candyTotal + WorkBot.bitName + "其中拉人奖励为" +
                            candyInvite + WorkBot.bitName + "红包奖励" + String.format("%.3f", redReward));
                } else {
                    TelegramUser telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(update.getMessage().getFrom().getId());
                    if (telegramUser != null) {
                        double candyTotal = telegramUser.getToken();
                        double candyInvite = this.getUserAllInviteReward(update.getMessage().getFrom().getId());
                        double redReward = this.getUserAllReward(update.getMessage().getFrom().getId());

                        this.sendMessage(this.update.getMessage().getChatId(), update.getMessage().getFrom().getFirstName() +
                                "您好，您共拥有" + candyTotal + WorkBot.bitName + "其中拉人奖励为" +
                                candyInvite + WorkBot.bitName + "红包奖励" + String.format("%.3f", redReward) + "\n 但您还没有绑定我们的空投助手，立即绑定，领取token");
                    } else {
                        TelegramUser telegramUserNew = new TelegramUser();
                        telegramUserNew.setToken(0.0);
                        telegramUserNew.setTelegramid(update.getMessage().getFrom().getId());
                        WorkBot.telegramUserMapper.insert(telegramUserNew);
                        this.sendMessage(this.update.getMessage().getChatId(), update.getMessage().getFrom().getFirstName() +
                                "您好,您未获得任何奖励，参与游戏、绑定空投助手可获得大量" + WorkBot.bitName);
                    }
                }
            } else if (texts[0].equals("/key")) {
                this.sendRedPaper(texts);
            }else if(update.getMessage().getText().substring(0,7).equals("/guess_")){
                int guessId = Integer.parseInt(update.getMessage().getText().substring(7).replace("@"+this.getBotUsername(),""));
                this.myGuess(guessId);
            }
        }
        return false;
    }

    //每隔一段时间自动获取adminlist 、 删除1分钟之内没说话的用户的msg
    Thread thread = new Thread() {
        public void run() {
            while (true) {
                try {
                    GetChatAdministrators getChatAdministrators = new GetChatAdministrators();
                    getChatAdministrators.setChatId(chatId);
                    ArrayList<ChatMember> list = new ArrayList<>();
                    try {
                        ArrayList<ChatMember> mylist  = execute(getChatAdministrators); // Call method to send the message
                        if (mylist != null && mylist.size() >= 1) {
                            for(int i=0; i< mylist.size(); i++) {
                                list.add(mylist.get(i));
                            }
                        }
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                    Thread.sleep(2 * 1000); //2s

                    GetChatAdministrators getChatAdministrators1 = new GetChatAdministrators();
                    getChatAdministrators1.setChatId(-1001320417482L);
                    try {
                        ArrayList<ChatMember> mylist = execute(getChatAdministrators1); // Call method to send the message
                        if (mylist != null && mylist.size() >= 1) {
                            for(int i=0; i< mylist.size(); i++) {
                                list.add(mylist.get(i));
                            }
                       }
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                    Thread.sleep(2 * 1000); //2s

                    GetChatAdministrators getChatAdministrators2 = new GetChatAdministrators();
                    getChatAdministrators1.setChatId(-1001298598358L);
                    try {
                        ArrayList<ChatMember> mylist = execute(getChatAdministrators2); // Call method to send the message
                        if (mylist != null && mylist.size() >= 1) {
                            for(int i=0; i< mylist.size(); i++) {
                                list.add(mylist.get(i));
                            }
                        }
                    } catch (TelegramApiException e) {
                        e.printStackTrace();
                    }
                    BotMethodSwitch.adminList = list;
                    Thread.sleep(2 * 60 * 1000); //两分钟
                    //删除垃圾
                    for (Map.Entry<Integer, Date> entry : BotMethodSwitch.userTalkInOneMin.entrySet()) {
                        if (entry.getValue().getTime() + 60 * 1000 < new Date().getTime()) {
                            BotMethodSwitch.spamCount.remove(entry.getKey());
                        }
                        System.out.println("key： " + entry.getKey() + " and value： " + entry.getValue());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    };



    public Thread getThread() {
        return this.thread;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(BotMethodSwitch.sendMsgStartMin * 1000 * 60);
            while (BotMethodSwitch.sendMsgTimes == -1 || BotMethodSwitch.sendMsgTimes > 0)
                if (BotMethodSwitch.botMethod.get("useSendMsgOnTime")) {
                    this.sendMessage(chatId, BotMethodSwitch.sendMsgOnTimeStr);
                    Thread.sleep(BotMethodSwitch.sendMsgOnTime * 1000 * 60);  //几分钟
                    if (BotMethodSwitch.sendMsgTimes > 0) {
                        BotMethodSwitch.sendMsgTimes--;
                    }
                }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public int differDayQty(Date Date1, Date Date2) {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.clear();
        calendar.setTime(Date1);
        int day1 = calendar.get(java.util.Calendar.DAY_OF_YEAR);
        int year1 = calendar.get(java.util.Calendar.YEAR);
        calendar.setTime(Date2);
        int day2 = calendar.get(java.util.Calendar.DAY_OF_YEAR);
        int year2 = calendar.get(java.util.Calendar.YEAR);
        if (year1 == year2) {//同一年
            return day2 - day1;
        } else if (year1 < year2) {//Date1<Date2
            int days = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年
                    days += 366;
                } else {
                    days += 365;
                }
            }
            return days + (day2 - day1);
        } else {//Date1>Date2
            int days = 0;
            for (int i = year2; i < year1; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    days += 366;
                } else {
                    days += 365;
                }
            }
            return 0 - days + (day2 - day1);
        }
    }

    public void sendRewardUsers(String token, Long chatId) {
        String msg = "口令红包: " + token + "\n";
        Reward reward = RewardUtil.hashMap.get(token);
        msg += reward.getAmount() + "/" + RewardUtil.userMap.get(token).size() + "已领" + " O(∩_∩)O" + " \n";
        msg += "__ 时间 __  |  ____ 昵称 ____  |  __ 数额 __ \n";
        for (RewardUser rewardUser : RewardUtil.userMap.get(token).values()) {
            msg += "---------------------------------------------------- \n ";
            SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
            String mytime = ft.format(rewardUser.getGetTime());
            msg += mytime + " | " + rewardUser.getUsername() + " | " + rewardUser.getReward() + "\n";
        }
        this.sendMessage(chatId, msg);
    }

    public Double getUserAllReward(int userId) {
        List<Double> list = rewardUserMapper.findAllReward(userId + "");
        double allMoney = 0;
        for (Double money : list) {
            allMoney += money;
        }
        return allMoney;
    }

    public Double getUserAllInviteReward(int userId) {
        double candyInvite = 0;
        List<InviteReward> list = inviteRewardMapper.selectCandyByInviterId(userId);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                candyInvite += list.get(i).getToken();
            }
        }
        return candyInvite;
    }

    public void sendRedPaper(String texts[]) {
        //验证口令是否存在
        String username = update.getMessage().getFrom().getFirstName() + " " + update.getMessage().getFrom().getLastName();
        username = username.replace("null", "");
        if (RewardUtil.hashMap.containsKey(texts[1])) {
            Reward myReward = RewardUtil.hashMap.get(texts[1]);
            //检查对应token的红包是否领取完毕
            if (RewardUtil.userMap.get(texts[1]).size() < myReward.getAmount()) {

                //检查对应token的红包中是否已被该用户领取
                if (!RewardUtil.userMap.get(texts[1]).containsKey(update.getMessage().getFrom().getId())) {
                    //分发钱包
                    HashMap list = RewardUtil.userMap.get(texts[1]);
                    RewardUser rewardUser = new RewardUser();
                    Date dNow = new Date();
                    rewardUser.setGetTime(dNow);
                    //rewardUser.setId(0);
                    rewardUser.setUsername(username);
                    rewardUser.setUserid(update.getMessage().getFrom().getId() + "");
                    rewardUser.setToken(texts[1]);
                    int times = RewardUtil.timesMap.get(texts[1]);
                    rewardUser.setReward(RewardUtil.redPacketMap.get(texts[1]).get(times));

                    //存入数据库
                    rewardUserMapper.insert(rewardUser);
                    List<Users> usersList = usersMapper.selectByTelegramId(update.getMessage().getFrom().getId());

                    RewardUtil.timesMap.put(texts[1], times + 1);
                    list.put(update.getMessage().getFrom().getId(), rewardUser);
                    RewardUtil.userMap.put(texts[1], list);
                    String text = "@" + username + " ,恭喜您,获得" + rewardUser.getReward() + bitName
                            + ",还剩" + (myReward.getAmount() - RewardUtil.userMap.get(texts[1]).size()) + "份红包";
                    if (usersList != null && usersList.size() == 1) {
                        Users users = usersList.get(0);
                        users.setCandynum(users.getCandynum() + rewardUser.getReward());
                        usersMapper.updateByPrimaryKey(users);
                    } else {
                        TelegramUser telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(update.getMessage().getFrom().getId());
                        if (telegramUser != null) {
                            telegramUser.setToken(telegramUser.getToken() + rewardUser.getReward());
                        } else {
                            TelegramUser telegramUserNew = new TelegramUser();
                            telegramUserNew.setToken(rewardUser.getReward());
                            telegramUserNew.setTelegramid(update.getMessage().getFrom().getId());
                            WorkBot.telegramUserMapper.insert(telegramUserNew);
                        }
                        text += ",您还未绑定我们的推广助手，赶快绑定领取token，完成任务获得更多奖励吧";

                    }
                    this.sendMessage(update.getMessage().getChatId(), text);
                    //最后一个人领完红包就报出红包情况
                    if (RewardUtil.userMap.get(texts[1]).size() == myReward.getAmount()) {
                        this.sendRewardUsers(texts[1], update.getMessage().getChatId());
                    }
                } else {
                    this.sendMessage(update.getMessage().getChatId(), "@" + username +
                            " ,您已领取了此红包,已获得" +
                            RewardUtil.userMap.get(texts[1]).get(update.getMessage().getFrom().getId()).getReward() + bitName +
                            ",请留意下次红包,输入/mine 查看共获得多少红包"
                    );
                }
            } else {
                this.sendMessage(update.getMessage().getChatId(), "@" + username +
                        "此红包已领取完,请留意下次红包");
            }

        } else {
            String text = "@" + username + " 您好,口令有误或红包已拿完,输入/mine 查看共获得多少红包";
            this.sendMessage(update.getMessage().getChatId(), text);
        }
    }

    public boolean openRed(String TokenName, int amount, double rewardTotal) {
        if (!RewardUtil.hashMap.containsKey(TokenName)) {
            Date dNow = new Date();
            Reward reward = new Reward();
            reward.setGetTime(dNow);
            reward.setToken(TokenName);
            reward.setAmount(amount);
            reward.setRewardtotal(rewardTotal);
            System.out.println(reward.toString());

            //存入数据库
            rewardMapper.insert(reward);
            //加入Reward到hashma中
            RewardUtil.hashMap.put(TokenName, reward);
            //初始化用户列表
            HashMap<String, RewardUser> list = new HashMap<>();
            //加入到usermap
            RewardUtil.userMap.put(reward.getToken(), list);
            //初始化次数
            RewardUtil.timesMap.put(TokenName, 0);
            //生成随机钱包
            RewardUtil.redPacketMap.put(reward.getToken(), RedPacketUtil.getList(reward.getRewardtotal(), reward.getAmount()));
            this.sendMessage(-1001389649632L, "红包来拉！有" + reward.getAmount() + "份，共" + reward.getRewardtotal() + bitName + ". \n 输入口令领取：/key " + reward.getToken());
            return true;
        } else {
            return false;
        }
    }

    //发信息、发按钮
    public boolean openGussing(File photo, String question, double tokenTotal, double tokenTimes, List<String> answer, Date endTime) {

        String answerCountToString = "";
        for (int i = 0; i < answer.size(); i++) {
            answerCountToString += answer.get(i);
            answerCountToString += "**";
        }
        answerCountToString = answerCountToString.substring(0, answerCountToString.length() - 2);

        //存储到数据库
        Guess guess = new Guess();
        int guessId = WorkBot.guessMapper.selectNum() + 1;
        guess.setId(guessId);
        guess.setAnswer(answerCountToString);
        guess.setEndtime(endTime);
        SimpleDateFormat ft = new SimpleDateFormat ("MM.dd HH:mm");
        String openMsg ="竞猜来拉~~~~答对即赢得大量奖励！结束时间:"+ft.format(endTime)+"\n"+"问题："+question + "\n" + "本次官方注入" + tokenTotal + WorkBot.bitName + "到奖池中,最小单注" + tokenTimes + WorkBot.bitName + "\n" + "查询命令: /guess_" + guessId;
        guess.setQuestion(question);
        guess.setStarttime(new Date());
        guess.setTokentimes(tokenTimes);
        guess.setTokentotal(tokenTotal);
        guess.setPhotopath(photo.getAbsolutePath());

        WorkBot.guessMapper.insert(guess);

        BotMethodSwitch.guessId.add(guessId);

        SendPhoto sendPhoto = new SendPhoto();
        sendPhoto.setNewPhoto(photo);
        sendPhoto.setCaption(openMsg);
        sendPhoto.setChatId(chatId);
        InlineKeyboardMarkup replyKeyboardMarkup = new InlineKeyboardMarkup();
        List<List<InlineKeyboardButton>> rows = new ArrayList<>();
        List<InlineKeyboardButton> row = new ArrayList<>();
        String answerCount[] = {"", "一注", "十注", "梭哈"};
        String callBack[] = {"1", "2", "3"};
        for (int i = 0; i < answer.size(); i++) {
            row = new ArrayList<>();
            InlineKeyboardButton button = new InlineKeyboardButton();
            button.setText(answer.get(i));
            button.setCallbackData(guessId + "**" + answer.get(i) + "**" + 0);
            row.add(button);
            for (int j = 1; j < 4; j++) {
                InlineKeyboardButton button1 = new InlineKeyboardButton();
                button1.setText(answerCount[j]);
                System.out.println(answerCount[j]);
                button1.setCallbackData(guessId + "**" + answer.get(i) + "**" + callBack[j - 1]);
                row.add(button1);
            }
            rows.add(row);
        }
        replyKeyboardMarkup.setKeyboard(rows);
        sendPhoto.setReplyMarkup(replyKeyboardMarkup);
        System.out.println(replyKeyboardMarkup.toString());
        try {
            this.sendPhoto(sendPhoto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //到时间移除guessId
        EndGuessThread endGuessThread = new EndGuessThread(guessId, endTime);
        endGuessThread.start();
        return true;
    }


    //管理员选择竞猜结果并结算
    public boolean closeGuessing(int guessId, String answerChose) {
        if (BotMethodSwitch.guessId.contains(guessId)) {
            BotMethodSwitch.guessId.remove(new Integer(guessId));
        }
        Guess guess = WorkBot.guessMapper.selectByPrimaryKey(guessId);
        String answer[] = guess.getAnswer().split("\\*\\*");
        System.out.println(answerChose + "---");
        for (int i = 0; i < answer.length; i++) {
            if (answer[i].equals(answerChose)) {
                guess.setAnswerfinal(answerChose);
            }
        }
        if (guess.getAnswerfinal() == null || guess.getAnswerfinal().equals("")) {
            return false;
        }

        List<GuessUser> guessUserList = WorkBot.guessUserMapper.selectByGuessId(guessId);
        List<GuessUser> guessUserWinList = new ArrayList<>();
        // System.out.println(guessUserList.size());
        double tokenTotalFinal = guess.getTokentotal();
        int tokenTimes = 0;
        int winTimes = 0;
        List<Integer> userCount = new ArrayList<>();
        for (int i = 0; i < guessUserList.size(); i++) {
            System.out.println("here");
            tokenTotalFinal += guessUserList.get(i).getGuesstoken();
            tokenTimes += guessUserList.get(i).getGuesstimes();
            if (guessUserList.get(i).getAnswer().equals(answerChose)) {
                guessUserWinList.add(guessUserList.get(i));
                winTimes += guessUserList.get(i).getGuesstimes();
            }
            if (!userCount.contains(guessUserList.get(i).getTelegramid())) {
                userCount.add(guessUserList.get(i).getTelegramid());
            }
        }

        //每注赢多少
        double tokenTimesWin = tokenTotalFinal / winTimes;
        List<Integer> winCount = new ArrayList<>();
        for (int i = 0; i < guessUserWinList.size(); i++) {
            List<Users> usersList = WorkBot.usersMapper.selectByTelegramId(guessUserWinList.get(i).getTelegramid());
            if (usersList != null && usersList.size() == 1) {
                Users users = usersList.get(0);
                users.setCandynum(users.getCandynum() + guessUserWinList.get(i).getGuesstimes() * tokenTimesWin);
                WorkBot.usersMapper.updateByPrimaryKey(users);
            } else {
                TelegramUser telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(guessUserWinList.get(i).getTelegramid());
                telegramUser.setToken(telegramUser.getToken() + guessUserWinList.get(i).getGuesstimes() * tokenTimesWin);
                WorkBot.telegramUserMapper.updateByPrimaryKey(telegramUser);
            }
            guessUserWinList.get(i).setReward(guessUserWinList.get(i).getGuesstimes() * tokenTimesWin);
            WorkBot.guessUserMapper.updateByPrimaryKey(guessUserWinList.get(i));
            if (!winCount.contains(guessUserWinList.get(i).getTelegramid())) {
                winCount.add(guessUserWinList.get(i).getTelegramid());
            }
        }
        guess.setTokentotalfinally(tokenTotalFinal);
        guess.setTokentimestotal(tokenTimes);
        guess.setWincount(winCount.size());
        guess.setJoincount(userCount.size());

        WorkBot.guessMapper.updateByPrimaryKey(guess);

        //sendMsg
        SendPhoto sendPhoto = new SendPhoto();
        sendPhoto.setNewPhoto(new File(guess.getPhotopath()));
        String msg = guess.getQuestion() + "\n" +"此问题竞猜结算"+ "\n" + "-------------" + "\n";
        msg += "本次竞猜正确选项是" + guess.getAnswerfinal() + "\n";
        msg += "本次竞猜单注投注金额为" + guess.getTokentimes() + WorkBot.bitName + ",官方注入" + guess.getTokentotal() + "\n";
        msg += "总奖金为" + guess.getTokentotalfinally() + "\n";
        msg += "共有" + guess.getJoincount() + "人参与竞猜," + "总投注" + guess.getTokentimestotal() + "\n";
        msg += "有" + guess.getWincount() + "人猜中,总获奖注数" + winTimes + "\n";
        msg += "查询命令: " + "/guess_" + guessId;
        sendPhoto.setCaption(msg);
        sendPhoto.setChatId(chatId);
        try {
            this.sendPhoto(sendPhoto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    //处理用户投注
    public boolean hasGuessing() {
        if(BotMethodSwitch.botMethod.get("useGuessing")){
            int id = update.getCallbackQuery().getFrom().getId();
            String callback = update.getCallbackQuery().getData();
            String callbackList[] = callback.split("\\*\\*");
            boolean isUsers = false;
            boolean isTelegram = false;
            double hasToken = 0;
            TelegramUser telegramUser = new TelegramUser();
            List<Users> usersList = new ArrayList<>();
            Users users = new Users();
            //在投注这一期
            if (BotMethodSwitch.guessId.contains(Integer.parseInt(callbackList[0]))) {
                //查看是否有此用户
                usersList = WorkBot.usersMapper.selectByTelegramId(id);
                if (usersList != null && usersList.size() == 1) {
                    isUsers = true;
                    users = usersList.get(0);
                    hasToken = users.getCandynum();
                } else {
                    telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(id);
                    if (telegramUser != null) {
                        isTelegram = true;
                        hasToken = telegramUser.getToken();
                    }
                }
                //若有此用户
                if (isUsers || isTelegram) {
                    int guessTimes = 0;
                    double guessToken = 0;
                    double nowToken = 0;
                    GuessUser guessUser = new GuessUser();
                    guessUser.setGuessid(Integer.parseInt(callbackList[0]));
                    guessUser.setAnswer(callbackList[1]);
                    guessUser.setTelegramid(id);
                    guessUser.setGettime(new Date());

                    Guess guess = WorkBot.guessMapper.selectByPrimaryKey(Integer.parseInt(callbackList[0]));
                    //区分投注多少
                    if (callbackList[2].equals("1")) {           //一注
                        if (hasToken >= guess.getTokentimes()) {
                            guessTimes = 1;
                            guessToken = guess.getTokentimes();
                        }
                    } else if (callbackList[2].equals("2")) {      //十注
                        if (hasToken >= guess.getTokentimes() * 10) {
                            guessTimes = 10;
                            guessToken = guess.getTokentimes() * 10;
                        }
                    } else if (callbackList[2].equals("3")) {      //梭哈
                        if (hasToken >= guess.getTokentimes()) {
                            guessTimes = new Double(hasToken / guess.getTokentimes()).intValue();
                            guessToken = guessTimes * guess.getTokentimes();
                        }
                    }
                    //判断是否够钱投了注
                    if (guessTimes != 0) {
                        nowToken = hasToken - guessToken;
                        guessUser.setGuesstimes(guessTimes);
                        guessUser.setGuesstoken(guessToken);
                        WorkBot.guessUserMapper.insert(guessUser);
                        if (isUsers) {
                            users.setCandynum(nowToken);
                            WorkBot.usersMapper.updateByPrimaryKey(users);
                            this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您成功投了" + guessTimes + "注," + "您还剩" + nowToken + "个" + WorkBot.bitName);
                        } else if (isTelegram) {
                            telegramUser.setToken(nowToken);
                            WorkBot.telegramUserMapper.updateByPrimaryKey(telegramUser);
                            this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您成功投了" +
                                    guessTimes + "注," + "您还剩" + nowToken + "个" + WorkBot.bitName + "绑定糖果助手可得更多积分");
                        }
                    } else {
                        this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您的token不足，您目前拥有" + hasToken + "个" + WorkBot.bitName);
                    }
                } else {
                    TelegramUser telegramUser1 = new TelegramUser();
                    telegramUser1.setToken(0.0);
                    telegramUser1.setTelegramid(update.getCallbackQuery().getFrom().getId());
                    WorkBot.telegramUserMapper.insert(telegramUser1);
                    this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您的token不足，您目前拥有" + 0 + "个" + WorkBot.bitName);
                }
                //操作
                //创建telegram,您还未获得任何token，您可以。。
            }
            //不在此期
            else {
                this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，此竞猜已结束,发送/guess_" + callbackList[0] + " ,即可查看自己投注情况");
            }
            return true;
        }
        return false;
    }

    //发送多次竞猜
    public boolean sendGuess(int guessId) {
        Guess guess = WorkBot.guessMapper.selectByPrimaryKey(guessId);
        SendPhoto sendPhoto = new SendPhoto();
        sendPhoto.setChatId(chatId);
        sendPhoto.setNewPhoto(new File(guess.getPhotopath()));
        List<GuessUser> guessUserList = WorkBot.guessUserMapper.selectByGuessId(guessId);
        List<Integer> userCount = new ArrayList<>();
        int tokenTimesCount = 0;
        double tokenTotalNow = guess.getTokentotal();
        if (guessUserList != null && guessUserList.size() >= 1) {
            for (int i = 0; i < guessUserList.size(); i++) {
                tokenTimesCount += guessUserList.get(i).getGuesstimes();
                tokenTotalNow += guessUserList.get(i).getGuesstoken();
                if (!userCount.contains(guessUserList.get(i).getTelegramid())) {
                    userCount.add(guessUserList.get(i).getTelegramid());
                }
            }
        }
        String openMsg = guess.getQuestion() + "\n" + "本次官方注入" + guess.getTokentotal() + WorkBot.bitName + "到奖池中,单注" + guess.getTokentimes() + WorkBot.bitName + "\n" + "查询命令: /guess_" + guessId;
        openMsg += "\n -------------------- \n 已有" + userCount.size() + "人参加,共投注" + tokenTimesCount + ",目前奖池为" + tokenTotalNow + WorkBot.bitName;
        sendPhoto.setCaption(openMsg);
        InlineKeyboardMarkup replyKeyboardMarkup = new InlineKeyboardMarkup();
        List<List<InlineKeyboardButton>> rows = new ArrayList<>();
        List<InlineKeyboardButton> row = new ArrayList<>();
        String answerCount[] = {"", "一注", "十注", "梭哈"};
        String callBack[] = {"1", "2", "3"};
        String answer[] = guess.getAnswer().split("\\*\\*");
        for (int i = 0; i < answer.length; i++) {
            row = new ArrayList<>();
            InlineKeyboardButton button = new InlineKeyboardButton();
            button.setText(answer[i]);
            button.setCallbackData(guessId + "**" + answer[i] + "**" + 0);
            row.add(button);
            for (int j = 1; j < 4; j++) {
                InlineKeyboardButton button1 = new InlineKeyboardButton();
                button1.setText(answerCount[j]);
                System.out.println(answerCount[j]);
                button1.setCallbackData(guessId + "**" + answer[i] + "**" + callBack[j - 1]);
                row.add(button1);
            }
            rows.add(row);
        }
        replyKeyboardMarkup.setKeyboard(rows);
        sendPhoto.setReplyMarkup(replyKeyboardMarkup);
        System.out.println(replyKeyboardMarkup.toString());
        try {
            this.sendPhoto(sendPhoto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    //guess_1 查看投注情况
    public boolean myGuess(int guessId) {
        List<GuessUser> guessUserList = WorkBot.guessUserMapper.selectUserInGuess(guessId, this.update.getMessage().getFrom().getId());
        Guess guess = WorkBot.guessMapper.selectByPrimaryKey(guessId);
        String msg = update.getMessage().getFrom().getFirstName() + "您好，您的投注情况： \n";
        double win = 0.0;
        if (guessUserList != null && guessUserList.size() > 0) {
            for (int i = 0; i < guessUserList.size(); i++) {
                msg += guessUserList.get(i).getAnswer() + " - " + guessUserList.get(i).getGuesstimes() + "注 - 花费" + guessUserList.get(i).getGuesstoken() + WorkBot.bitName + "\n";
                if(guessUserList.get(i).getReward()!=null){
                    win += guessUserList.get(i).getReward();
                }
            }
        } else {
            msg += "没有投注，赶快投注获得奖励吧";
        }
        msg += "------------------ \n";
        if (guess.getAnswerfinal() != null && !guess.getAnswerfinal().equals("")) {
            msg += "本次竞猜正确答案为:" + guess.getAnswerfinal()+"/n";
            if (win == 0) {
                msg += "很遗憾，您未赢得本次投注，再接再厉！";
            } else {
                msg += "恭喜您赢得了"+win+WorkBot.bitName;
            }

        } else {
            msg += "本次竞猜还未结束，关注群内动态即可得知结果";
        }
        this.sendMessage(chatId,msg);
        return true;
    }

    public boolean addToken(int telegramId,double token){
        List<Users> usersList = WorkBot.usersMapper.selectByTelegramId(telegramId);
        if(usersList!=null&&usersList.size()==1){
            usersList.get(0).setCandynum(usersList.get(0).getCandynum()+token);
            WorkBot.usersMapper.updateByPrimaryKey(usersList.get(0));
        }else{
            TelegramUser telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(telegramId);
            if(telegramUser!=null){
                telegramUser.setToken(telegramUser.getToken()+token);
                WorkBot.telegramUserMapper.updateByPrimaryKey(telegramUser);
            }else{
                TelegramUser telegramUserNew = new TelegramUser();
                telegramUserNew.setTelegramid(telegramId);
                telegramUserNew.setToken(token);
                WorkBot.telegramUserMapper.insert(telegramUserNew);
            }
        }
        return true;
    }

    //签到
    public boolean checkIn(){
        if(BotMethodSwitch.botMethod.get("useCheckIn")){
            if(update.getMessage().getText().equals("/签到")||update.getMessage().getText().equals("签到")){
                List<CheckIn> checkInList = WorkBot.checkInMapper.selectByTelegramId(update.getMessage().getFrom().getId());
                if(checkInList!=null&&checkInList.size()>0){
                    CheckIn checkIn = new CheckIn();
                    checkIn = checkInList.get(checkInList.size()-1); //获取最新签到
                    if(this.differDayQty(checkIn.getGettime(),new Date())!=0){
                        CheckIn checkInNew = new CheckIn();
                        checkInNew.setToken(BotMethodSwitch.checkInToken);
                        checkInNew.setTelegramid(update.getMessage().getFrom().getId());
                        checkInNew.setGettime(new Date());
                        WorkBot.checkInMapper.insert(checkInNew);

                        this.addToken(update.getMessage().getFrom().getId(),checkInNew.getToken());

                        this.sendMessage(chatId,update.getMessage().getFrom().getFirstName()+"签到成功，获得"+checkInNew.getToken()+WorkBot.bitName);
                        return true;
                    }else {
                        this.sendMessage(chatId,update.getMessage().getFrom().getFirstName()+"您好，您今天已签到");
                    }

                }else {
                    CheckIn checkIn = new CheckIn();
                    checkIn.setGettime(new Date());
                    checkIn.setTelegramid(update.getMessage().getFrom().getId());
                    checkIn.setToken(BotMethodSwitch.checkInToken);
                    WorkBot.checkInMapper.insert(checkIn);

                    this.addToken(update.getMessage().getFrom().getId(),checkIn.getToken());

                    this.sendMessage(chatId,update.getMessage().getFrom().getFirstName()+"您好，您今天签到成功，获得"+checkIn.getToken()+WorkBot.bitName);
                    return true;
                }
                return false;
            }else {
                return false;
            }
        }else {
            return false;
        }

    }

    //说话送token
    public boolean chatToken(){
        if(BotMethodSwitch.botMethod.get("useChatToken")){
            ChatToken chatToken = WorkBot.chatTokenMapper.selectByPrimaryKey(update.getMessage().getFrom().getId());
            if(chatToken!=null){
                if(differDayQty(chatToken.getGettime(),chatToken.getGettime())==0){  //今天说过话
                    if(chatToken.getDaychattimes()<BotMethodSwitch.chatDayTimes){
                        chatToken.setGettime(new Date());
                        chatToken.setDaychattimes(chatToken.getDaychattimes()+1);
                        WorkBot.chatTokenMapper.updateByPrimaryKey(chatToken);
                        this.addToken(chatToken.getTelegramid(),BotMethodSwitch.chatToken);
                    }
                }else { //今天没说过
                    chatToken.setDaychattimes(1);
                    chatToken.setGettime(new Date());
                    WorkBot.chatTokenMapper.updateByPrimaryKey(chatToken);
                    this.addToken(chatToken.getTelegramid(),BotMethodSwitch.chatToken);
                }
            }else {
                ChatToken chatTokenNew = new ChatToken();
                chatTokenNew.setTelegramid(update.getMessage().getFrom().getId());
                chatTokenNew.setDaychattimes(1);
                chatTokenNew.setGettime(new Date());

                WorkBot.chatTokenMapper.insert(chatTokenNew);
                this.addToken(chatTokenNew.getTelegramid(),BotMethodSwitch.chatToken);
            }
            return true;
        }else {
            return true;
        }
    }
}